import {getUserInfoByUserDDId} from '@/api/login'
import {useLoading} from '@/hooks/loading'
import deepClone from '@/libs/deepClone'
import {getDDUsers} from '@/libs/dingding'
import {ant_design_vue} from '@/libs/global/antDesignVue'
import {checkIsPhone, str2num} from '@/libs/toolkit'
import {computed, defineComponent, PropType, reactive, watch, onMounted} from 'vue'
import {TargetWeight} from '../input/targetWeight'
import {CnNormalP} from '../text'
import {DrawerContent, DrawerFooter} from './public'

const {message} = ant_design_vue

const PmTargetEnactDrawer = defineComponent({
  name: 'PmTargetEnactDrawer',
  props: {
    type: {
      type: String as PropType<'add' | 'edit'>,
      default: 'add'
    },
    title: {
      type: String,
      required: true
    },
    placement: {
      type: String as PropType<'top' | 'right' | 'bottom' | 'left'>,
      default: 'right'
    },
    visible: {
      type: Boolean,
      deafult: false
    },
    defaultPmGroupDimensionTarget: Object as PropType<Evaluation.PmGroupDimensionTarget>,
    showUtils: {
      type: Boolean,
      default: true
    },
    showAppointScore: {
      type: Boolean,
      default: true
    },
    /**选择指定人员时需要排除的人员Id列表 */
    excludeUserIds: Array as PropType<string[]>,

    // 目标制定阶段禁止输入
    setTargetDisabled: Boolean,

    // 目标确认阶段禁止输入
    setTargetByLeaderDisabled: Boolean
  },
  emits: {
    'update:visible': (data: boolean): boolean => true,
    confirm: (data: Evaluation.PmGroupDimensionTarget): boolean => true
  },
  setup(props, {emit}) {
    const {loading, startLoading, closeLoading} = useLoading()

    onMounted(() => {
      console.log('showAppointScore', props.showAppointScore)
    })

    let state = reactive<{
      visible: boolean
      pmGroupDimensionTarget: Omit<
        Evaluation.PmGroupDimensionTarget,
        'pmGroupDimensionTargetWeight'
      > & {
        pmGroupDimensionTargetWeight: number | undefined
      }
      appointUser: {userDDId: string | undefined; userName: string}
    }>({
      visible: false,
      pmGroupDimensionTarget: {
        isBonus: 0,
        pmGroupDimensionTargetRange: '0-100',
        appointScoreSign: 0,
        appointUserDDId: undefined,
        pmGroupDimensionTargetId: -1,
        pmGroupDimensionTargetName: '',
        pmGroupDimensionId: -1,
        pmGroupDimensionTargetStand: '',
        pmGroupDimensionTargetWeight: undefined,
        pmGroupDimensionTargetDesc: '',
        isMustSelect: 0,
        sort: 0
      },
      appointUser: {
        userDDId: '',
        userName: ''
      }
    })
    const isPhone = computed(() => checkIsPhone())

    // 指标名称是否禁止输入
    const targetNameDisabled = computed(() => {
      if (state.pmGroupDimensionTarget.isMustSelect === 1) return true
      return false
    })

    // 指标标准是否禁止输入
    const targetStandDisabled = computed(() => {
      if (state.pmGroupDimensionTarget.isMustSelect === 1) return true

      return false
    })

    // 指标权重是否禁止输入
    const targetWeightDisabled = computed(() => {
      if (state.pmGroupDimensionTarget.isBonus === 1) return true
      return false
    })

    // watch(
    //   () => props.visible,
    //   n => {
    //     state.visible = n
    //   },
    //   {immediate: true}
    // )

    // watch(
    //   () => state.visible,
    //   n => {
    //     emit('update:visible', n)
    //   }
    // )

    watch(
      () => props.defaultPmGroupDimensionTarget,
      n => {
        resetAppointUser()
        console.log('指标修改 传入值', n)

        if (n) {
          state.pmGroupDimensionTarget = deepClone(n) as Evaluation.PmGroupDimensionTarget

          state.appointUser.userDDId = n.appointUserDDId
          if (n.appointUserDDId) {
            startLoading()
            getUserInfoByUserDDId({userDDId: n.appointUserDDId})
              .then(res => {
                state.appointUser.userName = res.data.userName
                closeLoading()
              })
              .catch(err => {
                closeLoading()
              })
          }
        } else {
          resetPmGroupDimensionTarget()
        }
      },
      {
        immediate: true
      }
    )

    function resetPmGroupDimensionTarget() {
      state.pmGroupDimensionTarget = {
        isBonus: 0,
        pmGroupDimensionTargetRange: '0-100',
        appointScoreSign: 0,
        appointUserDDId: undefined,
        pmGroupDimensionTargetId: -1,
        pmGroupDimensionTargetName: '',
        pmGroupDimensionId: -1,
        pmGroupDimensionTargetStand: '',
        pmGroupDimensionTargetWeight: undefined,
        pmGroupDimensionTargetDesc: '',
        isMustSelect: 0,
        sort: 0
      }
    }

    function setAppointUser(data: {userDDId: string | undefined; userName: string}) {
      state.appointUser = data
      state.pmGroupDimensionTarget.appointUserDDId = data.userDDId
    }

    function resetAppointUser() {
      state.appointUser = {userDDId: undefined, userName: ''}
      state.pmGroupDimensionTarget.appointUserDDId = undefined
    }

    function checkData(): false | Evaluation.PmGroupDimensionTarget {
      if (!state.pmGroupDimensionTarget.pmGroupDimensionTargetName) {
        message.error({
          content: '请输入指标名称'
        })
        return false
      }

      if (
        state.pmGroupDimensionTarget.pmGroupDimensionTargetWeight &&
        state.pmGroupDimensionTarget.pmGroupDimensionTargetWeight < 0
      ) {
        message.error({
          content: '请输入指标权重'
        })
        return false
      }

      if (!state.pmGroupDimensionTarget.pmGroupDimensionTargetStand) {
        message.error({
          content: '请输入指标考核标准'
        })
        return false
      }
      return {
        isBonus: state.pmGroupDimensionTarget.isBonus || 0,
        pmGroupDimensionTargetRange: state.pmGroupDimensionTarget.pmGroupDimensionTargetRange,
        appointScoreSign: state.pmGroupDimensionTarget.appointScoreSign,
        appointUserDDId: state.pmGroupDimensionTarget.appointUserDDId,
        pmGroupDimensionTargetId: state.pmGroupDimensionTarget.pmGroupDimensionTargetId,
        pmGroupDimensionTargetName: state.pmGroupDimensionTarget.pmGroupDimensionTargetName,
        pmGroupDimensionId: state.pmGroupDimensionTarget.pmGroupDimensionId,
        pmGroupDimensionTargetStand: state.pmGroupDimensionTarget.pmGroupDimensionTargetStand,
        pmGroupDimensionTargetWeight:
          state.pmGroupDimensionTarget.pmGroupDimensionTargetWeight || 0,
        pmGroupDimensionTargetDesc: state.pmGroupDimensionTarget.pmGroupDimensionTargetDesc,
        isMustSelect: state.pmGroupDimensionTarget.isMustSelect,
        sort: state.pmGroupDimensionTarget.sort
      }
    }

    function handleConfirmAndContinue() {
      let checkResult = checkData()
      if (!checkResult) return
      emit('confirm', checkResult)
      resetPmGroupDimensionTarget()
    }

    function handleConfirm() {
      let checkResult = checkData()
      if (!checkResult) return
      emit('confirm', checkResult)
      resetPmGroupDimensionTarget()
      handleCancel()
    }

    function handleCancel() {
      // state.visible = false
      emit('update:visible', false)
    }

    return () => (
      <a-drawer
        width={isPhone.value ? '80%' : 600}
        // v-model={[state.visible, 'visible']}
        visible={props.visible}
        title={props.title}
        placement={props.placement}
        onClose={handleCancel}
      >
        <DrawerContent>
          <a-form
            labelAlign='right'
            labelCol={{
              // span: state.pmGroupDimensionTarget.appointScoreSign === 1 ? 5 : 4
              span: 4
            }}
            wrapperCol={{
              // span: state.pmGroupDimensionTarget.appointScoreSign === 1 ? 19 : 20
              span: 20
            }}
          >
            <a-form-item label='指标名称：' required>
              <a-input
                disabled={targetNameDisabled.value}
                class='rounded-4 '
                v-model={[state.pmGroupDimensionTarget.pmGroupDimensionTargetName, 'value']}
              ></a-input>
            </a-form-item>
            <a-form-item label='考核标准：' required>
              <a-textarea
                disabled={targetStandDisabled.value}
                class='rounded-4 '
                v-model={[state.pmGroupDimensionTarget.pmGroupDimensionTargetStand, 'value']}
                rows={4}
              ></a-textarea>
            </a-form-item>
            <a-form-item label='权重：' required>
              <TargetWeight
                v-model={[state.pmGroupDimensionTarget.pmGroupDimensionTargetWeight, 'value']}
                disabled={targetWeightDisabled.value}
              ></TargetWeight>
            </a-form-item>

            {props.showUtils ? (
              <a-form-item label='必选：'>
                <a-switch
                  v-model={[state.pmGroupDimensionTarget.isMustSelect, 'checked']}
                  checkedValue={1}
                  unCheckedValue={0}
                ></a-switch>
              </a-form-item>
            ) : null}

            {props.showAppointScore ? (
              <a-form-item label='指定评分人：'>
                <a-switch
                  v-model={[state.pmGroupDimensionTarget.appointScoreSign, 'checked']}
                  checkedValue={1}
                  unCheckedValue={0}
                ></a-switch>
              </a-form-item>
            ) : null}

            {state.pmGroupDimensionTarget.appointScoreSign === 1 ? (
              <a-form-item>
                <div class='flex items-center gap-x-8 flex-wrap'>
                  <div class='w-113'>
                    <a-button
                      onClick={() => {
                        getDDUsers({
                          users: state.appointUser.userDDId ? [state.appointUser.userDDId] : [],
                          multiple: false
                        })
                          .then(res => {
                            if (res !== 'cancel') {
                              if (props.excludeUserIds) {
                                if (props.excludeUserIds.includes(res[0].emplId)) {
                                  message.warning('请选择被考核人或评分人以外的人员！')
                                } else {
                                  setAppointUser({userDDId: res[0].emplId, userName: res[0].name})
                                }
                              } else {
                                setAppointUser({userDDId: res[0].emplId, userName: res[0].name})
                              }
                            }
                          })
                          .catch(err => {})
                      }}
                    >
                      选择评分人
                    </a-button>
                  </div>

                  <div>
                    <a-spin spinning={loading.value}>
                      {state.appointUser.userName ? (
                        <a-tag
                          closable
                          onClose={() => {
                            resetAppointUser()
                          }}
                        >
                          {state.appointUser.userName}
                        </a-tag>
                      ) : null}
                    </a-spin>
                  </div>
                </div>
              </a-form-item>
            ) : null}

            {state.pmGroupDimensionTarget.isBonus === 1
              ? [
                  <a-form-item label='加分项：'>
                    <a-switch
                      v-model={[state.pmGroupDimensionTarget.isBonus, 'checked']}
                      checkedValue={1}
                      unCheckedValue={0}
                      disabled={true}
                    ></a-switch>
                  </a-form-item>,
                  <a-form-item label='评分区间：'>
                    <a-input
                      class='rounded-4 '
                      v-model={[state.pmGroupDimensionTarget.pmGroupDimensionTargetRange, 'value']}
                    ></a-input>
                    <CnNormalP class='mt-8'>
                      评分区间输入格式示例为：0-5, 表示用户可输入的范围为0到5
                    </CnNormalP>
                  </a-form-item>
                ]
              : null}

            {/* <a-form-item label='备注：'>
              <a-input
                class='rounded-4 '
                v-model={[state.pmGroupDimensionTarget.pmGroupDimensionTargetDesc, 'value']}
              ></a-input>
            </a-form-item> */}
          </a-form>

          <DrawerFooter>
            <div class='w-full h-full flex items-center justify-end gap-x-12'>
              <a-button class='rounded-4' onClick={handleCancel}>
                取消
              </a-button>
              <a-button
                class='rounded-4 bg-primary text-white'
                type='primary'
                onClick={handleConfirm}
              >
                提交
              </a-button>

              {props.type === 'add' ? (
                <a-button
                  class='rounded-4 bg-primary text-white'
                  type='primary'
                  onClick={handleConfirmAndContinue}
                >
                  提交并继续添加
                </a-button>
              ) : null}
            </div>
          </DrawerFooter>
        </DrawerContent>
      </a-drawer>
    )
  }
})
export default PmTargetEnactDrawer
